<template>
  <div style="min-height: 500px;">
    <splitpanes class="default-theme" @resize="resize" @resized="resized">
      <pane min-size="25" size="40">
        <a-spin size="large" :spinning="spinning">
          <div class="operation-btn-sticky">
            <a-input-search
              v-model="searchValue"
              style="margin-bottom: 8px;width: 70%"
              placeholder="搜索"
              @change="searchTreeNode"
            />
            <a-button v-if="isEdit" type="primary" style="float:right; margin-right: 50px;" @click="resetPaperIndex">刷新</a-button>
          </div>
          <div id="scollBox" style="overflow:auto;height:650px;">
            <!-- :show-line="true"
              :show-icon="true" -->
            <a-tree
              v-if="treeData.length > 0"
              :tree-data="treeData"
              :defaultExpandAll="true"
              :defaultSelectedKeys="defaultSelectedKey"
              @select="onSelect"
              :expanded-keys="expandedKeys"
              @expand="onExpand"
              :checkable="false"
              draggable
              @dragstart="treeDragStart"
            >
              <template slot="title" slot-scope="item">
                <div
                  v-if="item.type == Tp_dostype.VOLUME"
                  :class="[activeTypeIndex === item.id ? 'list-item-active' : '']"
                  @dragenter="typeDragenter($event, item)"
                  @dragover="typeDragover($event, item)"
                  @dragleave="typeDragleave()"
                  class="algin_justity_center"
                >
                  <div v-if="expandedKeys.includes(item.key) " class="custom-icon-fold algin_justity_center">
                    －
                  </div>
                  <div v-else-if="!expandedKeys.includes(item.key) " class="custom-icon-open algin_justity_center">
                    ＋
                  </div>
                  <span class="tree-title-root ant-tree-title-margin" v-if="item.name.indexOf(searchValue) > -1">
                    {{ item.name.substr(0, item.name.indexOf(searchValue)) }}
                    <span style="color: #f50">{{ searchValue }}</span>
                    {{ item.name.substr(item.name.indexOf(searchValue) + searchValue.length) }}
                  </span>
                  <span class="tree-title-root" v-else>{{ item.name }}</span>
                  <span style="padding-left:10px"> {{ pageIndexShow(Tp_dostype.VOLUME, item) }}</span>

                  <a-dropdown class="drop-menu-style" v-if="isEdit">
                    <a class="ant-dropdown-link" @click="e => e.preventDefault()">操作 <a-icon type="down" /> </a>
                    <a-menu slot="overlay">
                      <a-menu-item @click="addItem(item, Tp_dostype.VOLUME, true)">
                        新增分卷
                      </a-menu-item>
                      <a-menu-item v-show="item.deleted == YesNoValue.YES" @click="modifyItem(item)">
                        修改分卷
                      </a-menu-item>
                      <a-menu-item @click="addItem(item, Tp_dostype.TERM, false)">
                        新增类别
                      </a-menu-item>
                      <a-menu-item v-show="item.deleted == YesNoValue.YES" @click="deleteItem(item)">
                        删除分卷
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
                </div>
                <div
                  v-if="item.type == Tp_dostype.TERM"
                  :class="[activeTypeIndex === item.id ? 'list-item-active' : '']"
                  @dragenter="typeDragenter($event, item)"
                  @dragover="typeDragover($event, item)"
                  @dragend="typeDragend($event, item)"
                  @dragleave="typeDragleave()"
                  @drop="typeDrop($event, item)"
                  class="algin_justity_center"
                >
                  <div v-if="expandedKeys.includes(item.key) " class="custom-icon-fold algin_justity_center">
                    －
                  </div>
                  <div v-else-if="!expandedKeys.includes(item.key) " class="custom-icon-open algin_justity_center">
                    ＋
                  </div>
                  <span class="tree-title-child ant-tree-title-margin" v-if="item.name.indexOf(searchValue) > -1">
                    {{ item.name.substr(0, item.name.indexOf(searchValue)) }}
                    <span style="color: #f50">{{ searchValue }}</span>
                    {{ item.name.substr(item.name.indexOf(searchValue) + searchValue.length) }}
                  </span>
                  <span class="tree-title-child" v-else>{{ item.name }}</span>
                  <span style="padding-left:10px"> {{ pageIndexShow(Tp_dostype.TERM, item) }}</span>

                  <a-dropdown class="drop-menu-style" v-if="isEdit">
                    <a class="ant-dropdown-link" @click="e => e.preventDefault()">操作 <a-icon type="down" /> </a>
                    <a-menu slot="overlay">
                      <a-menu-item @click="addItem(item, Tp_dostype.TERM, true)">
                        新增类别
                      </a-menu-item>
                      <a-menu-item @click="modifyItem(item)" v-show="item.deleted == YesNoValue.YES">
                        修改类别
                      </a-menu-item>
                      <a-menu-item @click="deleteItem(item)" v-show="item.deleted == YesNoValue.YES">
                        删除类别
                      </a-menu-item>
                      <a-menu-item @click="addFile(item)">
                        新增材料
                        <!-- <a-upload
                          :accept="acceptFileType"
                          :data="item"
                          :customRequest="file => uploadFile(file)"
                          :before-upload="file => beforeUpload(file)"
                          name="file"
                          :showUploadList="false"
                          :multiple="false"
                        >
                          <span>新增材料</span>
                        </a-upload> -->
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
                </div>
                <div
                  v-if="item.type == Tp_dostype.FILE"
                  :class="[activeTypeIndex === item.id ? 'list-item-active' : '']"
                  @dragenter="typeDragenter($event, item)"
                  @dragover="typeDragover($event, item)"
                  @dragleave="typeDragleave()"
                >
                  <div class="hover-div">
                    <a-icon type="book" />
                    <span class="tree-title-child-inner" v-if="item.name.indexOf(searchValue) > -1">
                      {{ item.name.substr(0, item.name.indexOf(searchValue)) }}
                      <span style="color: #f50">{{ searchValue }}</span>
                      {{ item.name.substr(item.name.indexOf(searchValue) + searchValue.length) }}
                    </span>
                    <span class="tree-title-child-inner" v-else>
                      {{ item.name }}
                    </span>
                    <span style="padding-left:10px"> {{ pageIndexShow(Tp_dostype.FILE, item) }}</span>
                    <a-icon type="download" @click.stop="downloadFile(item)" style="padding: 10px; 0px"></a-icon>
                    <!-- <a-popconfirm  placement="right" title="是否删除?" @confirm="() => deleteItem(item)" > -->
                    <a-icon
                      type="delete"
                      v-if="isEdit && item.deleted == YesNoValue.YES"
                      class="hover-delete"
                      @click="deleteItem(item)"
                    />
                    <!-- </a-popconfirm> -->
                  </div>
                </div>
              </template>
              <!-- 展开图标作用域插槽 -->
              <template slot="switcherIcon" slot-scope="item">
                <div class="icon-add" v-if="item.type != Tp_dostype.FILE">＋</div>
                <div v-else style="display: none;"></div>
              </template>
            </a-tree>
            <a-empty v-else description="暂无文件" />
          </div>
        </a-spin>
      </pane>
      <pane min-size="25" style="overflow: auto;">
        <div class="pane_right">
          <a-tabs default-active-key="1" style="padding:0px 20px;">
            <a-tab-pane key="1" tab="材料预览" force-render>
              <iframe
                id="iframe"
                v-show="fileUrl != ''"
                :src="fileUrl"
                width="100%"
                height="650px"
                scrolling="yes"
                frameborder="0"
              />
              <a-empty v-show="fileUrl == ''" description="暂无文件，无法预览" style="width:100%; height:650px" />
            </a-tab-pane>
            <a-tab-pane key="2" tab="未归类文件" force-render>
              <div style="overflow:auto;height:650px;">
                <a-list item-layout="horizontal" :data-source="noArchiveMaterials">
                  <a-list-item slot="renderItem" slot-scope="item">
                    <a-list-item-meta style="margin-top: 10px;">
                      <span slot="title"> 
                        <a-icon class="file_icon" slot="avatar" type="file-text" />
                        <span class="file_title">
                          {{ Tp_proctype[Number(item.customer.proctype)].name + "-" + item.customer.name }} 
                        </span>
                      </span>
                      <!-- {{ item.materials }} -->
                      <div slot="description" style="margin-top:10px;margin-left: 20px;" v-for="(material, index) in item.materials">
                        <!-- {{ material }} -->
                        <a type="link" draggable="true" @click="previewNoArchiveDoc(material)" @dragstart="fileDragStart($event, material)" @drag="fileDrag"
                          @dragend="fileDragend($event, material)">
                          {{ material.file.filename }}
                        </a>
                      </div>
                    </a-list-item-meta>
                  </a-list-item>
                </a-list>
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>
      </pane>
    </splitpanes>
    <ArchiveDocModify
      ref="archiveDocModify"
      @saveNodeCallback="saveNodeCallback"
      @modifyNodeCallback="modifyNodeCallback"
    ></ArchiveDocModify>

    <MultiUploadBasic ref="multiUploadBasic" @importFileFun="importFileFun"></MultiUploadBasic>

  </div>
</template>
  
<script>
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import ArchiveDocModify from '@/views/archive/ArchiveDocModify.vue'
import {
  getDocTreeByApplyid,
  saveMaterialToTree,
  saveNoStoreMaterialToTree,
  updateTreeNodeIndex
} from '@/api/archive/apl_archive.js'
import { queryNoArchiveCustomerMaterial } from '@/api/accept/aprv_process_materials.js'
import { Tp_dostypeValue } from '@/enumeration/Tp_dostype.js'
import { YesNoValue } from '@/enumeration/YesNo'
import { deleteTreeNode } from '@/api/archive/apl_archive'
import { kkfilePreview } from '@/utils/util'
import { Tp_proctype } from '@/enumeration/Tp_proctype'
import { FILETYPE, FILESIZE } from '@/store/mutation-types'
export default {
  props: {
    applyid: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    serviceType: {
      type: Number,
      required: true
    }
  },

  data() {
    return {
      isResize: false,
      treeData: [],
      cloneTreeData: [],
      Tp_dostype: Tp_dostypeValue,
      YesNoValue: YesNoValue,
      Tp_proctype: Tp_proctype,
      fileUrl: '',
      searchValue: '', // 查询节点值
      spinning: false, // 加载动画
      activeTypeIndex: null, // 选中的分类下标
      isTreeDrag: false, //是否是树元素drag
      treeDragNode: '', //drag元素的id
      defaultSelectedKey: [], // 默认选择的树节点的key
      noArchiveMaterials: [], //未分类文件
      dargFile: {}, // 未分类拖动的文件
      acceptFileType: FILETYPE,
      expandedKeys: [], // 展开指定的树节点
      uploadSelectTreeNode: {}
    }
  },
  created() {
    this.init()
  },
  components: {
    Splitpanes,
    Pane,
    ArchiveDocModify,
    MultiUploadBasic: () => import('@/views/materials/multiUpload/MultiUploadBasic.vue')
  },
  methods: {
    init() {
      this.getDocTreeByApplyid()
      // 查询未归类材料
      this.getNoArchiveMaterial()
    },
    searchTreeNode() {
      const value = this.searchValue
      this.filter(this.treeData, value)
      if (value == '') {
        this.treeData = JSON.parse(JSON.stringify(this.cloneTreeData)) //cloneTreeData 接口返回深拷贝的数据
      }
    },
    filter(nodes, query) {
      // 条件就是节点的title过滤关键字
      let predicate = function(node) {
        if (node.name.indexOf(query) > -1) {
          return true
        } else {
          return false
        }
      }
      if (!(nodes && nodes.length)) {
        return []
      }
      let newChildren = []
      for (let node of nodes) {
        // 以下两个条件任何一个成立，当前节点都应该加入到新子节点集中
        // 1. 子孙节点中存在符合条件的，即 subs 数组中有值
        // 2. 自己本身符合条件
        // let subs = this.filter(node.children, query);
        // if (predicate(node)) {
        //   newChildren.push(node);
        // } else if (subs && subs.length) {
        //   node.children = subs;
        //   newChildren.push(node);
        // }
        // 以下只需要考虑自身的节点满足条件即可,不用带上父节点
        if (predicate(node)) {
          newChildren.push(node)
          node.children = this.filter(node.children, query)
        } else {
          newChildren.push(...this.filter(node.children, query))
        }
      }
      this.treeData = newChildren //this.treeData接口返回的数组
      return newChildren.length ? newChildren : []
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
    },
    // 树节点触发选择
    onSelect(selectedKeys, info) {
      if ( info.selectedNodes && info.selectedNodes.length > 0 && info.selectedNodes[0] && info.selectedNodes[0].data.props.file) {
        let filePath = info.selectedNodes[0].data.props.file.path
        this.fileUrl = kkfilePreview(filePath)
      } else {
        this.fileUrl = ''
      }
    },
    setSlot(treeData, expandedKeys) {
      console.log('树形数据', treeData)
      treeData.forEach(element => {
        element.scopedSlots = { title: 'title' }
        if (element.type != this.Tp_dostype.FILE) {
          if (element.children && element.children.length > 0) {
            expandedKeys.push(element.key)
          }
        }
        if (element.children != null && element.children != undefined && element.children.length > 0) {
          this.setSlot(element.children, expandedKeys)
        }
      })
    },
    pageIndexShow(type, item) {
      if (type == this.Tp_dostype.VOLUME || type == this.Tp_dostype.TERM) {
        if (
          item.startindex != null &&
          item.startindex != undefined &&
          item.endindex != null &&
          item.endindex != undefined
        ) {
          if (item.startindex != item.endindex) {
            return '【' + item.startindex + '~' + item.endindex + '】页'
          } else {
            return '【' + item.endindex + '】页'
          }
        }
      } else {
        if (item.endindex != null && item.endindex != undefined) {
          return item.endindex + ' 页'
        }
      }
    },
    /**
     * 重置当前的索引
     */
    resetPaperIndex() {
      this.spinning = true
      // 重新查询未归档数据
      this.getNoArchiveMaterial()
      updateTreeNodeIndex({ applyid: this.applyid }).then(res => {
        this.spinning = false
        if (res.code == 0) {
          this.treeData = res.data
          this.expandedKeys = []
          this.setSlot(this.treeData, this.expandedKeys)
          console.log('当前选择的数据', this.expandedKeys)
          //搜索框的值为空时，重新赋值
          this.cloneTreeData = JSON.parse(JSON.stringify(this.treeData))
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 按照applyid查询对应的树层级结构
    getDocTreeByApplyid() {
      this.spinning = true
      getDocTreeByApplyid({ applyid: this.applyid, isEdit: this.isEdit, serviceType: this.serviceType }).then(res => {
        this.spinning = false
        if (res.code == 0) {
          this.treeData = res.data
          this.expandedKeys = []
          this.setSlot(this.treeData, this.expandedKeys)
          console.log('当前选择的数据', this.expandedKeys)
          // 默认树节点选中第一条数据
          // 选择默认的第一个材料的数据
          let firstNode = this.getFirstNode(this.treeData)
          if (firstNode) {
            // 默认选中第一个节点
            this.defaultSelectedKey[0] = firstNode[0].id;
            this.fileUrl = kkfilePreview(firstNode[0].file.path)
          }
          //搜索框的值为空时，重新赋值
          this.cloneTreeData = JSON.parse(JSON.stringify(this.treeData))
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 查找树的第一个非分类节点
    getFirstNode (treeData) {
      var temp = []
      var forFn = function (arr) {
        if (arr && arr.length > 0) {
          if (arr[0].file) {
            temp.push(arr[0])
          }
          if (arr[0].children) {
            forFn(arr[0].children)
          }
        }
      }
      forFn(treeData)
      return temp
    },
    /**
     * 查询自定义材料文件及对应的分类
     */
    getNoArchiveMaterial() {
      queryNoArchiveCustomerMaterial({ applyid: this.applyid}).then(res => {
        if (res.code == 0) {
          this.noArchiveMaterials = res.data
          console.log('未归档数据' , this.noArchiveMaterials)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    /**
     * 展示未归档的材料文件
     */
    previewNoArchiveDoc(material) {
      if (material) {
        console.log('文件预览', material)
        window.open(kkfilePreview(material.file.path))
      } else {
        this.$message.error('当前无法预览')
      }
    },

    addItem(item, treeNodeType, isSameLevel) {
      let formObj = {}
      formObj.isModify = false
      if (isSameLevel) {
        formObj.parentId = item.parentid
      } else {
        formObj.parentId = item.id
      }
      formObj.treeNodeType = treeNodeType
      formObj.applyid = this.applyid
      if (treeNodeType == this.Tp_dostype.VOLUME) {
        formObj.isRoot = true
      } else {
        formObj.isRoot = false
      }
      this.$refs.archiveDocModify.init(formObj)
    },
    saveNodeCallback(treeNode, isRoot) {
      this.addTreeChildDataAfter(treeNode, treeNode.parentid, isRoot)
    },
    modifyItem(item) {
      let formObj = {}
      formObj.isModify = true
      formObj.parentId = item.parentid
      formObj.treeNodeType = item.type
      formObj.treeNodeId = item.id
      formObj.treeNodeName = item.name
      formObj.applyid = this.applyid
      this.$refs.archiveDocModify.init(formObj)
    },
    modifyNodeCallback(treeNode) {
      this.modifyTreeChildDataAfter(treeNode, treeNode.parentid)
    },
    deleteItem(item) {
      this.$confirm({
        title: '是否删除该数据？',
        onOk: () => {
          this.spinning = true
          deleteTreeNode({ treeNodeId: item.id }).then(res => {
            this.spinning = false
            if (res.code == 0) {
              this.$message.success('删除成功')
              this.deleteTreeChildDataAfter(item.id)
              // 重新查询右侧未归位文件
              this.getNoArchiveMaterial()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    saveMaterialToTree(form) {
      this.spinning = true
      saveMaterialToTree(form).then(res => {
        this.spinning = false
        if (res.code == 0) {
          this.$message.success('保存文件成功')
          let result = res.data
          this.addTreeChildDataAfter(result, result.parentid, false)
          // 重新查询右侧未归位文件
          this.getNoArchiveMaterial()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    resize() {
      this.isResize = true
    },
    resized() {
      this.isResize = false
    },
    /*** 材料导入开始 ** */
    addFile(item) {
      this.uploadSelectTreeNode = item
      this.$refs.multiUploadBasic.importVisible = true
    },
    /**
     * 确定保存导入数据
     */
    importFileFun (importFileList) {
      console.log('importFileList', importFileList)
      let files = []
      importFileList.forEach((item) => {
        files.push(item)
      })
      this.uploadFile(importFileList)
    },
    /**
     * 上传附件,没有用到附件请删除
     */
    uploadFile (importFileList) {
      let params = {
        applyid: this.applyid,
        parentId: this.uploadSelectTreeNode.id
      }
      this.$refs.multiUploadBasic.loading = true
      saveNoStoreMaterialToTree(params, importFileList).then(res => {
        this.spinning = false
        console.log('res', res)
        if (res.code !== 0) {
          this.$message.error('文件上传失败')
        } else {
          const fileResultList = res.data
          if (fileResultList && fileResultList.length > 0) {
            fileResultList.forEach(file => {
                // 对应树节点新增一条数据
                this.addTreeChildDataAfter(file, file.parentid, false)
            })
          }
          this.$message.success('上传成功')
          this.$refs.multiUploadBasic.handleCancel()
        }
      }).finally(() => {
        this.$refs.multiUploadBasic.loading = false
      })
    },
    downloadFile (fileItem) {
      const file = fileItem.file
      const x = new XMLHttpRequest()
      x.open('GET', file.path, true)
      x.responseType = 'blob'
      x.onload = function (e) {
        const url = window.URL.createObjectURL(x.response)
        const a = document.createElement('a')
        a.href = url
        a.download = file.filename
        a.click()
      }
      x.send()
    },
    // 前端树新增后触发方法
    addTreeChildDataAfter(childData, parentId, isRoot) {
      let treeData = JSON.parse(JSON.stringify(this.cloneTreeData))
      this.addTreeChildData(childData, parentId, treeData, isRoot)
      // 重新赋值
      this.treeData = treeData
      if (this.treeData && this.treeData.length > 0) {
        this.treeData.forEach((item, index) => {
          this.$set(this.treeData, index, item)
        })
      }
      this.cloneTreeData = JSON.parse(JSON.stringify(this.treeData))
      // 触发搜索
      this.searchTreeNode()
    },

    // 在树节点中新增一条数据 , 前端新增
    addTreeChildData(childData, parentId, treeData, isRoot) {
      console.log('新增节点数据', childData)
      if (isRoot) {
        childData.scopedSlots = { title: 'title' }
        treeData.push(childData)
      } else {
        if (parentId != null && parentId != undefined && parentId != '') {
          for (let index = 0; index < treeData.length; index++) {
            let element = treeData[index]
            if (element.id == parentId) {
              childData.scopedSlots = { title: 'title' }
              if (element.children != null && element.children != undefined && element.children.length > 0) {
                element.children.push(childData)
              } else {
                element.children = []
                element.children.push(childData)
              }
              break
            }
            if (element.children != null && element.children != undefined && element.children.length > 0) {
              this.addTreeChildData(childData, parentId, element.children, false)
            }
          }
        }
      }
    },
    // 前端树修改后触发方法
    modifyTreeChildDataAfter(childData, parentId) {
      let treeData = JSON.parse(JSON.stringify(this.cloneTreeData))
      this.modifyTreeChildData(childData, parentId, treeData)
      // 重新赋值
      this.treeData = treeData
      if (this.treeData && this.treeData.length > 0) {
        this.treeData.forEach((item, index) => {
          this.$set(this.treeData, index, item)
        })
      }
      this.cloneTreeData = JSON.parse(JSON.stringify(this.treeData))
      // 触发搜索
      this.searchTreeNode()
    },

    // 树节点修改一条数据，前端修改
    modifyTreeChildData(childData, parentId, treeData) {
      console.log('修改节点数据', childData)
      if (parentId != null && parentId != undefined && parentId != '') {
        for (let index = 0; index < treeData.length; index++) {
          let element = treeData[index]
          if (element.id == childData.id) {
            childData.scopedSlots = { title: 'title' }
            element.name = childData.name
            break
          }
          if (element.id == parentId) {
            childData.scopedSlots = { title: 'title' }
            // 修改
            if (element.children != null && element.children != undefined) {
              for (let k = 0; k < element.children.length; k++) {
                let child = element.children[k]
                if (child != null && child != undefined && child.id == childData.id) {
                  child.name = childData.name
                  break
                }
              }
            }
          }
          if (element.children != null && element.children != undefined && element.children.length > 0) {
            this.modifyTreeChildData(childData, parentId, element.children)
          }
        }
      }
    },
    // 前端树删除后触发方法
    deleteTreeChildDataAfter(childId) {
      let treeData = JSON.parse(JSON.stringify(this.cloneTreeData))
      this.deleteTreeChildData(childId, treeData)
      // 重新赋值
      this.treeData = treeData
      if (this.treeData && this.treeData.length > 0) {
        this.treeData.forEach((item, index) => {
          this.$set(this.treeData, index, item)
        })
      }
      this.cloneTreeData = JSON.parse(JSON.stringify(this.treeData))
      // 触发搜索
      this.searchTreeNode()
    },

    // 树节点删除一条数据，前端删除
    deleteTreeChildData(childId, treeData) {
      console.log('删除数据', childId)
      for (let index = 0; index < treeData.length; index++) {
        let element = treeData[index]
        if (element.id == childId) {
          treeData.splice(index, 1)
          // treeData = treeData.filter((x) => x.id !== childId);
          break
        }
        if (element.children != null && element.children != undefined && element.children.length > 0) {
          this.deleteTreeChildData(childId, element.children)
        }
      }
    },

    // 树节点获取对应的材料文本
    getMaterialInTreeById(treeData, treeNodeId) {
      if (treeData && treeData.length > 0) {
        for (let index = 0; index < treeData.length; index++) {
          let item = treeData[index]
          if (item.type == this.Tp_dostype.FILE) {
            if (item.id == treeNodeId) {
              return item
            }
          } else {
            if (item.children) {
              const findResult = this.getMaterialInTreeById(item.children, treeNodeId)
              if (findResult) return findResult
            } else {
              break
            }
          }
        }
      }
    },

    // 树控件drag触发
    treeDragStart(info) {
      this.isTreeDrag = true
      let treeNodeId = info.node.eventKey
      let treeNode = this.getMaterialInTreeById(this.treeData, treeNodeId)
      // 判断当前的文件名是否是封面文件 若是则提示无法拖动
      this.treeDragNode = treeNode
    },
    // 其他控件drag触发
    fileDragStart(e, item, index) {
      // this.activeCardIndex = index
      this.isTreeDrag = false
      this.dargFile = item
      // console.log('Start--------拖动源：拖动开始时触发----------')
    },
    fileDrag() {
      // console.log('fileDrag-------拖动源：拖动过程中触发-----------')
    },
    typeDragend(e, item) {},
    fileDragend(e, item, index) {
      // console.log('fileDragend-------拖动源：拖动结束触发-----------')
    },
    typeDragenter(e, item) {
      // let cardItem = this.cardList[this.activeCardIndex]
      if (item.type == this.Tp_dostype.VOLUME || item.type == this.Tp_dostype.FILE) {
        return
      }
      // console.log('typeDragenter-------拖动目标：被拖动元素进入到目标区域时触发-----------')
    },
    typeDragover(e, item) {
      e = e || event
      if (e.preventDefault) {
        e.preventDefault()
        this.activeTypeIndex = item.id
        // 判断当前移动的是否是特殊的文件，若是则不允许拖拽
        if (this.isEdit) {  
          if (this.isTreeDrag) {
            if (this.treeDragNode.name == '案卷封面.pdf' ||   this.treeDragNode.name == '卷内目录.pdf' ||   this.treeDragNode.name == '行政复议案件备考表（封底）.pdf') {
              e.dataTransfer.dropEffect = 'none' // 禁用拖拽到该区域
              return 
            } 
          }
          // 判断文件是否可以拖拽
          if (item.type == this.Tp_dostype.VOLUME || item.type == this.Tp_dostype.FILE) {
            e.dataTransfer.dropEffect = 'none' // 禁用拖拽到该区域
          } else {
            e.dataTransfer.dropEffect = 'move' //可拖拽到该区域
          }
        } else {
          e.dataTransfer.dropEffect = 'none' // 禁用拖拽到该区域
        }
      } else {
        e.returnValue = false
      }
      // console.log('typeDragover-------拖动目标：被拖动元素在目标区域移动时触发-----------')
    },
    typeDragleave() {},
    // drap结束
    typeDrop(e, item) {
      // 特殊情况，若当前的节点是对应的封面名称和对应的类型不为空，则提示无法拖拽
      if ((item.name.indexOf('案卷封面') > -1 || item.name.indexOf('卷内目录') > -1 || item.name.indexOf('行政复议案件备考表（封底）') > -1) && item.mattype != null && item.mattype != undefined) {
        this.$message.warning('当前类别无法拖拽修改')
        this.activeTypeIndex = ''
        return
      }
      //
      try {
        if (!this.isTreeDrag) {
          // 非树元素drag触发
          if (item.type == this.Tp_dostype.VOLUME || item.type == this.Tp_dostype.FILE) {
            return
          }
          let saveForm = {
            applyid: this.applyid,
            parentId: item.id,
            materialId: this.dargFile.attachid,
            materialName: this.dargFile.file.filename,
            deleted: this.YesNoValue.YES,
            mattype: ''
          }
          this.saveMaterialToTree(saveForm)
        } else {
          // 树元素drag触发
          // 删除原来的元素 ，然后再新增
          if (this.treeDragNode) {
            this.spinning = true
            deleteTreeNode({ treeNodeId: this.treeDragNode.id }).then(res => {
              if (res.code == 0) {
                this.deleteTreeChildDataAfter(this.treeDragNode.id)
                // 再保存数据
                let saveForm = {
                  applyid: this.applyid,
                  parentId: item.id,
                  materialId: this.treeDragNode.matid,
                  materialName: this.treeDragNode.name,
                  deleted: this.treeDragNode.deleted,
                  mattype: this.treeDragNode.mattype || '' // 自己上传材料该项为空
                }
                this.saveMaterialToTree(saveForm)
              } else {
                this.$message.error('拖拽失败')
              }
            })
          }
        }
      } finally {
        this.activeTypeIndex = ''
      }
      // console.log('typeDragenter-------拖动目标：释放鼠标时触发-----------')

    },
  }
}
</script>
  
<style lang="less" scoped>
.title-label {
  font-size: 16px;
  font-weight: 800;
  width: 200px;
  height: 40px;
  padding: 10px 20px;
}

.but_type {
  color: #1890ff !important;
  cursor: pointer;
  padding-left: 5px;
  padding-right: 5px;
}

.drop-menu-style {
  margin-left: 20px;
  display: inline-block;
}

::v-deep .splitpanes.default-theme .splitpanes__pane {
  background-color: #fff;
}

.tree-title-root {
  font-size: 16px;
  font-weight: 600;
}

.tree-title-child {
  font-size: 14px;
  font-weight: 550;
}

.tree-title-child-inner {
  font-size: 14px;
  color: #0072c6 !important;
}
.hover-delete {
  display: inline-block;
  padding-left: 20px;
  color: red !important;
}

.operation-btn-sticky {
  position: sticky;
  top: 0;
  z-index: 10;
}

.list-item-active {
  > span {
    background-color: #bae7ff !important;
  }
}

.file_title {
  display: inline-flex;
  text-align: center;
  font-size: 16px;
  margin-left: 10px;
  margin-top: 5px;
  position: absolute;
}
.file_icon {
  font-size: 25px;
}

::v-deep .ant-tree-child-tree > li:first-child {
  padding-top: 4px;
}
::v-deep .ant-tree-node-content-wrapper span {
  color: #2c2c2c;
}
/* 禁用状态文字 */
::v-deep li.ant-tree-treenode-disabled > .ant-tree-node-content-wrapper span {
  color: #2c2c2c;
}
::v-deep li.ant-tree-node-content-wrapper.ant-tree-node-selected {
  background-color: #bae7ff;
  height: 36px !important;
}
::v-deep .ant-tree-node-selected {
  height: 36px !important;
}

::v-deep .ant-tree-node-selected {
  height: 36px;
}

::v-deep .ant-tree-node-content-wrapper:hover {
  height: 36px;
}
.ant-tree-title-margin {
  margin-left: 20px;
}

.custom-icon-open,
.custom-icon-fold,
.icon-add {
  color: #fff;
  background-color: #0072c6;
  font-weight: 800;
  font-size: 16px !important;
}
/* 用文字图标覆盖展开图标实现效果 */
.custom-icon-open,
.custom-icon-fold {
  width: 14px;
  height: 14px;
  margin-left: -26px;
}
/* 文字偏移补充图标间距 */
.node_text {
  margin-left: -26px;
}
/* 折叠样式 */
.custom-icon-fold {
  background-color: #09c89f;
}
/* 自定义展开图标 */
.icon-add {
  width: 24px;
  height: 24px;
  opacity: 0;
}
</style>